package com.zhny.aiot.ksd.flow.plugin;

import com.zhny.aiot.ksd.flow.plugin.model.FlowStoreEntry;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import io.netty.buffer.ByteBuf;

public class FlowDevice extends ModbusNumDevice<FlowStoreEntry> {
    public FlowDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
    }

    @Override
    public FlowStoreEntry decode(ModemResponseMessage msg) {
        ByteBuf buf = msg.getData();
        Float flow1=buf.readFloat();
        Float flowSpeed1=buf.readFloat();
        Float percentage1=buf.readFloat();
        Float flowPercentage1=buf.readFloat();
        int totalFlowHig1=((buf.readByte() << 24) &0xff000000|
                (buf.readByte() << 16) &0x00ff0000|
                (buf.readByte() << 8) &0x0000ff00 |
                (buf.readByte()) & 0x000000ff);
        Float totalFlowLo1=buf.readFloat();
        Float totalFlow = totalFlowHig1 + totalFlowLo1;
        FlowStoreEntry entry = new FlowStoreEntry();
        entry.setFlow(String.format ("%.2f",flow1));
        entry.setFlowSpeed(String.format ("%.2f",flowSpeed1));
        entry.setTotalFlow( String.format ("%.2f",totalFlow));
        logger.info ("ksd-flow[{}]",entry);
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData ().readableBytes () == 24;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory ().getRequestMessage (getConfig ());
    }

    @Override
    protected void disposable() {

    }
}
